﻿using ScratchNet.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ScratchNet
{
    public class EDS2010SetOutputExpression : Expression
    {
        private static IOBoardContent _ioBoardContent = new IOBoardContent();

        public override string ReturnType => "any";
        public BoolOperator BoolOperator { get; set; }

        private static List<string> OutPutValues = new List<string>();
        public string OutPutValue { get; set; }


        public EDS2010SetOutputExpression()
        {
            BoolOperator = BoolOperator.TRUE;
        }
        public EDS2010SetOutputExpression(IOBoardContent ioBoardContent)
        {
            _ioBoardContent = ioBoardContent;
            BoolOperator = BoolOperator.TRUE;
            if (!OutPutValues.Any() && ioBoardContent.IOTypeCountDict.TryGetValue(LinkIOTypeEmParaDLL.DOut_HD, out var outputs))
            {
                for (int i = 1; i <= outputs.Count; i++)
                {
                    OutPutValues.Add($"output{i}");
                }
            }
            OutPutValue = OutPutValues.FirstOrDefault();
        }
        protected override Completion ExecuteImpl(ExecutionEnvironment enviroment)
        {
            return new Completion(null, SetBoolPin());
        }
        public override Descriptor Descriptor
        {
            get
            {
                Descriptor desc = new Descriptor();
                desc.Add(new TextItemDescriptor(this, "EDS2010 设置 DO", true));
                desc.Add(new SelectionItemDescriptor(this, "OutPutValue", OutPutValues, OutPutValues));
                desc.Add(new TextItemDescriptor(this, " 值 "));
                desc.Add(new SelectionItemDescriptor(this, "BoolOperator", new object[] { "TRUE", "FALSE", },
                    new object[] { BoolOperator.TRUE, BoolOperator.FALSE }));

                return desc;
            }
        }

        public override string Type
        {
            get { return "EDS2010SetOutputExpression"; }
        }

        private string SetBoolPin()
        {
            int index = UtilityExtension.GetNumberByString(OutPutValue) - 1;
            if (index < 0 || index >= _ioBoardContent.IOTypeCountDict[LinkIOTypeEmParaDLL.DOut_HD].Count)
            {
                return string.Empty;
            }

            int nSlaveNum = _ioBoardContent.IOTypeCountDict[LinkIOTypeEmParaDLL.DOut_HD][index].nSlaveNum;

            return ($"ComTaskManager.EthercatIOWriteClient.DOWrite({nSlaveNum}, {index}, {((int)BoolOperator)});");

        }
    }
}
